
/**
 * 工具组件 对原有的工具进行封装，自定义某方法统一处理
 * 
 * @author lgf 2018-4-10
 * @Url: www.dsesa.cn
 * @version 2.0v
 */
(function() {

    jp = {
			
	   /**使用jp.open代替top.layer.open，参数使用完全一致，请参照layer官网, 不在直接暴露layer在，jeeplus对layer进行统一封装**/
	   open:top.layer.open,
	   
	   /**通知方法，不阻塞浏览器当前窗口，四个级别 info,warning,error,success，图标不同，其余用法完全相同*/		
	   info:function(msg){
			return top.layer.msg(msg);
	   },
		
	   warning: function(msg){//通知
		   return top.layer.msg(msg, {icon:0});
	   },
	   
	   success:function(msg){
		   return top.layer.msg(msg, {icon:1});
	   },

	   error:function(msg){
		   return top.layer.msg(msg, {icon:2});
	   },
	   
	   //layer之外的另一个选择toast风格消息提示框,直接使用jp.toastr调用
	   toastr:(function(){
		   top.toastr.options = {
					  "closeButton": true,
					  "debug": false,
					  "progressBar": true,
					  "positionClass": "toast-top-right",
					  "onclick": null,
					  "showDuration": "200",
					  "hideDuration": "200",
					  "timeOut": "10000",
					  "extendedTimeOut": "1000",
					  "showEasing": "swing",
					  "hideEasing": "linear",
					  "showMethod": "fadeIn",
					  "hideMethod": "fadeOut"
					}
		   return top.toastr;
	   })(),
	   
	   //页面提示声音
	   voice:function() {
		    var audio = document.createElement("audio");
		    audio.src = ctxStatic+"/common/voice/default.wav";
		    audio.play();
	  },
	   
	   /**加载层，一直阻塞浏览器窗口，必须手动调用close方法关闭*/	   
	   loading:function(msg){
		   if(!msg){
			   msg = '正在提交，请稍等...';
		   }
		   
		  var index = top.layer.msg(msg, {
			  icon: 16
			  ,shade: 0.01,
			  time:999999999//设置超长时间
			});
		  
		  return index;
	   },
	   
	   close:function(index){
		   if(index){
			   top.layer.close(index);
		   }else{
			   top.layer.closeAll();
		   }
		   
	   },
	   
	   
	   /**alert弹出框，阻塞浏览器窗口*/
	   alert:function(msg){
		   top.layer.alert(msg, {
			    skin: 'layui-layer-lan'
			    ,area:['auto', 'auto']
			    ,icon: 0
			    ,closeBtn: 0
			    ,anim: 4 //动画类型
			  });
	   },
	   
	   /**询问框，阻塞浏览器窗口*/
	   confirm:function(msg, succFuc, cancelFuc){//msg:询问信息， succFuc：点‘是’调用的函数， errFuc:点‘否’调用的函数
		   top.layer.confirm(msg, 
		     {icon: 3, title:'系统提示', btn: ['是','否'] //按钮
		     }, function(index){
		    	 if (typeof succFuc == 'function') {
		    		 succFuc();
		 		}else{
		 			
		 			location = succFuc;
		 			jp.success("操作成功！", {icon:1});
		 		}
			     top.layer.close(index);
			 }, function(index){
				 if(cancelFuc)
					 cancelFuc();
			     top.layer.close(index);
			 });
		   
		   return false;
	   },

        prompt:function (title, href) {
            var index = top.layer.prompt({title: title, formType: 2}, function(text){
                if (typeof href == 'function') {
                    href(text);
                }else{
                    location = href + encodeURIComponent(text);
                }

                top.layer.close(index);
            });

        },
        //打开一个窗体
        windowOpen:function(url, name, width, height){
        var top=parseInt((window.screen.height-height)/2,10),left=parseInt((window.screen.width-width)/2,10),
            options="location=no,menubar=no,toolbar=no,dependent=yes,minimizable=no,modal=yes,alwaysRaised=yes,"+
                "resizable=yes,scrollbars=yes,"+"width="+width+",height="+height+",top="+top+",left="+left;
        window.open(url ,name , options);
   	 },

    // //打开对话框(添加修改)
	 //  openDialog: function(title,url,width,height, $table){
		// var auto = true;//是否使用响应式，使用百分比时，应设置为false
		// if(width.indexOf("%")>=0 || height.indexOf("%")>=0 ){
		// 	auto =false;
		// }
	 //   	top.layer.open({
	 //   	    type: 2,
	 //   	    area: [width, height],
	 //   	    title: title,
	 //   	    auto:auto,
	 //   	    maxmin: true, //开启最大化最小化按钮
	 //   	    content: url ,
	 //   	    btn: ['确定', '关闭'],
	 //   	    yes: function(index, layero){
	 //   	         var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
	 //   	         if(!$table){//如果不传递table对象过来，按约定的默认id获取table对象
	 //   	        	 $table = $('#table')
	 //   	         }
	 //   	         iframeWin.contentWindow.doSubmit($table, index);
	 //   		  },
	 //   	   cancel: function(index){
	 //   	      }
	 //   	});
	 //   },
    //
	 //   //打开对话框(查看)
	 //   openDialogView :function(title,url,width,height){
		//    var auto = true;//是否使用响应式，使用百分比时，应设置为false
    //        if(width.indexOf("%")>=0 || height.indexOf("%")>=0 ){
    //            auto =false;
    //        }
		// 	top.layer.open({
		// 		type: 2,
		// 		area: [width, height],
		// 		title: title,
		// 		auto:auto,
		// 		maxmin: true, //开启最大化最小化按钮
		// 		content: url ,
		// 		btn: ['关闭'],
		// 		cancel: function(index){
		// 		   }
		// 	});
	 //
	 //   },

        /**子表变颜色**/
        ckChangeRow:function(tbodyIds){
            var idarr = tbodyIds.split(",");
            $.each(idarr,function(idx,value){
                var trs = document.getElementById(value).getElementsByTagName("tr");
                for(var i=0;i<trs.length;i++){
                    $(trs[i]).on("click",function(){
                        $(trs).each(function(){
                            $(this).css("background-color","");
                        });
                        $(this).css("background-color","#93aaff");
                    });
                }
            })

        },

	   /**打开图片预览框**/
	   showPic:function(url){
           if(!/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(url)){
               jp.error("无法预览非图片文件");
           }else {
               var json = {
                   "data": [   //相册包含的图片，数组格式
                       {
                           "src": url, //原图地址
                       }
                   ]
               };
               top.layer.photos({
                   photos: json
                   ,anim: 0 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
               });
           }

		   
	   },
	   
	   /**用户选择框**/
        openUserSelectDialog:function(isMultiSelect, yesFuc){
            top.layer.open({
                type: 2,
                area: ['1100px', '560px'],
                title:"选择用户",
                auto:true,
                maxmin: true, //开启最大化最小化按钮
                content: ctx+"/sys/user/userSelect?isMultiSelect="+isMultiSelect,
                btn: ['确定', '关闭'],
                yes: function(index, layero){
                    var ids = layero.find("iframe")[0].contentWindow.getIdSelections();
                    var names = layero.find("iframe")[0].contentWindow.getNameSelections();
                    var loginNames = layero.find("iframe")[0].contentWindow.getLoginNameSelections();
                    if(ids.length ==0){
                        jp.warning("请选择至少一个用户!");
                        return;
                    }
                    // 执行保存
                    yesFuc(ids.join(","), names.join(","), loginNames.join(","));

                    top.layer.close(index);
                },
                cancel: function(index){
                    //取消默认为空，如需要请自行扩展。
                    top.layer.close(index);
                }
            });
        },

        /**款项选择框**/
        openCostSelectDialog:function(isMultiSelect, yesFuc){
            top.layer.open({
                type: 2,
                area: ['400px', '560px'],
                title:"选择款项",
                auto:true,
                maxmin: true, //开启最大化最小化按钮
                content: ctx+"/sys/archCostItem/costSelect?isMultiSelect="+isMultiSelect,
                btn: ['确定', '关闭'],
                yes: function(index, layero){
                    var ids = layero.find("iframe")[0].contentWindow.getIdSelections();
                    var labels = layero.find("iframe")[0].contentWindow.getLabelSelections();
                    if(ids.length ==0){
                        jp.warning("请选择至少一个款项!");
                        return;
                    }
                    // 执行保存
                    yesFuc(ids.join(","), labels.join(","));

                    top.layer.close(index);
                },
                cancel: function(index){
                    //取消默认为空，如需要请自行扩展。
                    top.layer.close(index);
                }
            });
        },

        /**角色选择框**/
        openRoleSelectDialog1:function(isMultiSelect, yesFuc){
            top.layer.open({
                type: 2,
                area: ['400px', '560px'],
                title:"选择角色",
                auto:true,
                maxmin: true, //开启最大化最小化按钮
                content: ctx+"/actSetting/roleSelect?isMultiSelect="+isMultiSelect,
                btn: ['确定', '关闭'],
                yes: function(index, layero){
                    var ids = layero.find("iframe")[0].contentWindow.getIdSelections();
                    if(ids.length ==0){
                        jp.warning("请选择至少一个款项!");
                        return;
                    }
                    // 执行保存
                    yesFuc(ids.join(","));

                    top.layer.close(index);
                },
                cancel: function(index){
                    //取消默认为空，如需要请自行扩展。
                    top.layer.close(index);
                }
            });
        },

        /**款项选择框**/
        openOutSelectDialog:function(isMultiSelect, yesFuc){
            top.layer.open({
                type: 2,
                area: ['1300px', '1000px'],
                title:"选择",
                auto:true,
                maxmin: true, //开启最大化最小化按钮
                content: ctx+"/buzz/outfactbill/outfactBill/outSelect?isMultiSelect="+isMultiSelect,
                btn: ['确定', '关闭'],
                yes: function(index, layero){
                    var ids = layero.find("iframe")[0].contentWindow.getIdSelections();
                    var data = layero.find("iframe")[0].contentWindow.getSelections();
                    if(ids.length ==0){
                        jp.warning("请选择至少一个数据!");
                        return;
                    }
                    // 执行保存
                    yesFuc(data);

                    top.layer.close(index);
                },
                cancel: function(index){
                    //取消默认为空，如需要请自行扩展。
                    top.layer.close(index);
                }
            });
        },

        /**单据款项选择框**/
        openObjCostSelectDialog:function(isMultiSelect,objectId, yesFuc){
            top.layer.open({
                type: 2,
                area: ['400px', '560px'],
                title:"选择款项",
                auto:true,
                maxmin: true, //开启最大化最小化按钮
                content: ctx+"/sys/objectCostItem/costSelect?isMultiSelect="+isMultiSelect+"&objectId="+objectId,
                btn: ['确定', '关闭'],
                yes: function(index, layero){
                    var data = layero.find("iframe")[0].contentWindow.getSelections();
                    if(data.length ==0){
                        jp.warning("请选择至少一个款项!");
                        return;
                    }
                    // 执行保存
                    yesFuc(data);

                    top.layer.close(index);
                },
                cancel: function(index){
                    //取消默认为空，如需要请自行扩展。
                    top.layer.close(index);
                }
            });
        },

        /**角色选择框**/
        openRoleSelectDialog:function(isMultiSelect, yesFuc){
            var url = ctx + "/sys/role/data";
            var fieldLabels = "角色名|英文名";
            var fieldKeys = "name|enname";
            top.layer.open({
                type: 2,
                area: ['800px', '500px'],
                title:"角色选择",
                auto:true,
                name:'friend',
                content: ctx+"/tag/gridselect?url="+encodeURIComponent(url)+"&fieldLabels="+encodeURIComponent(fieldLabels)+"&fieldKeys="+encodeURIComponent(fieldKeys)+"&searchLabels="+encodeURIComponent(fieldLabels)+"&searchKeys="+encodeURIComponent(fieldKeys)+"&isMultiSelected="+isMultiSelect,
                btn: ['确定', '关闭'],
                yes: function(index, layero){
                    var iframeWin = layero.find('iframe')[0].contentWindow; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var items = iframeWin.getSelections();
                    if(items == ""){
                        jp.warning("必须选择一条数据!");
                        return;
                    }
                    var ids = [];
                    var names = [];
                    for(var i=0; i<items.length; i++){
                        var item = items[i];
                        ids.push(item.id);
                        names.push(item.enname)
                    }
                    yesFuc(ids.join(","), names.join(","));
                    top.layer.close(index);//关闭对话框。
                },
                cancel: function(index){
                }
            });
        },
        dateFormat:function (timestamp, format) {
          var _this =  new Date(timestamp);
           var o = {
               "M+": _this.getMonth() + 1,
               // month
               "d+": _this.getDate(),
               // day
               "h+": _this.getHours(),
               // hour
               "m+": _this.getMinutes(),
               // minute
               "s+": _this.getSeconds(),
               // second
               "q+": Math.floor((_this.getMonth() + 3) / 3),
               // quarter
               "S": _this.getMilliseconds()
               // millisecond
           };
           if (/(y+)/.test(format) || /(Y+)/.test(format)) {
               format = format.replace(RegExp.$1, (_this.getFullYear() + "").substr(4 - RegExp.$1.length));
           }
           for (var k in o) {
               if (new RegExp("(" + k + ")").test(format)) {
                   format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
               }
           }
           return format;
       },
	    escapeHTML: function(a){  
	        a = "" + a;  
	        return a.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");;  
	    },  
	    /** 
	     * @function unescapeHTML 还原html脚本 < > & " ' 
	     * @param a - 
	     *            字符串 
	     */  
	    unescapeHTML: function(a){  
	        a = "" + a;  
	        return a.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&quot;/g, '"').replace(/&apos;/g, "'");  
	    }, 
	  //获取字典标签
	    getDictLabel : function(data, value, defaultValue){
	    	for (var i=0; i<data.length; i++){
	    		var row = data[i];
	    		if (row.value == value){
	    			return row.label;
	    		}
	    	}
	    	return defaultValue;
	    },
	    
	    post:function(url,data,callback){
			$.ajax({
	                url:url,
	                method:"post",
	                data:data,
	                error:function(xhr,textStatus){
	                	if(xhr.status == 0){
	                		jp.info("连接失败，请检查网络!")
	                	}else if(xhr.status == 404){
	                		var errDetail ="<font color='red'>404,请求地址不存在！</font>";
		                	top.layer.alert(errDetail , {
		                		  icon: 2,
		                		  area:['auto','auto'],
		                		  title:"请求出错"
		                	})
	                	}else if(xhr.status && xhr.responseText){
                            var errDetail ="<font color='red'>"+ xhr.responseText.replace(/[\r\n]/g,"<br>").replace(/[\r]/g,"<br>").replace(/[\n]/g,"<br>")+"</font>";
                            top.layer.alert(errDetail , {
                                icon: 2,
                                area:['80%','70%'],
                                title:xhr.status+"错误"
                            })
                        }else{
	                		var errDetail ="<font color='red'>未知错误!</font>";
		                	top.layer.alert(errDetail , {
		                		  icon: 2,
		                		  area:['auto','auto'],
		                		  title:"真悲剧，后台抛出异常了"
		                		})
	                	}
	                },
	                success:function(data,textStatus,jqXHR){
	                	if(data.indexOf == "_login_page_"){//登录超时
	                		location.reload(true);          
	                	}else{
	                		callback(data);
	                	}
	                }
           		 });
	    },
	    
	    get:function(url,callback){
			$.ajax({
	                url:url,
	                method:"get",
	                error:function(xhr,textStatus){
	                	if(xhr.status == 0){
	                		jp.info("连接失败，请检查网络!")
	                	}else if(xhr.status == 404){
	                		var errDetail ="<font color='red'>404,请求地址不存在！</font>";
		                	top.layer.alert(errDetail , {
		                		  icon: 2,
		                		  area:['auto','auto'],
		                		  title:"请求出错"
		                	})
	                	}else if(xhr.status && xhr.responseText){
                            var errDetail ="<font color='red'>"+ xhr.responseText.replace(/[\r\n]/g,"<br>").replace(/[\r]/g,"<br>").replace(/[\n]/g,"<br>")+"</font>";
                            top.layer.alert(errDetail , {
                                icon: 2,
                                area:['80%','70%'],
                                title:xhr.status+"错误"
                            })
                        }else{
	                		var errDetail ="<font color='red'>未知错误!</font>";
		                	top.layer.alert(errDetail , {
		                		  icon: 2,
		                		  area:['auto','auto'],
		                		  title:"真悲剧，后台抛出异常了"
		                		})
	                	}
	                	
	                },
	                success:function(data,textStatus,jqXHR){
                        if(data.indexOf == "_login_page_"){//返回首页内容代表登录超时
							top.layer.alert("登录超时！")
	                		location.reload(true);   
	                	}else{
	                		callback(data);
	                	}
	                	
	                }
           		 });
	    },
        /**
         * 格式化金额
         * @param var1
         * @param var2
         * @returns {string}
         */
        toFloat: function(var1,var2){
	        if(var1 == undefined || var1 == ""){
                var1 = "0";
            }
            var1 = parseFloat(var1).toFixed(var2); //obj=123456.789
            var left = var1.split(".")[0].split("").reverse();//left = ["6","5","4","3","2","1"]
            var right = var1.split(".")[1]; //right = "789"
            var total = new Array();
            for (var i = 0; i < left.length; i++) {
                total.push(left[i]);
                if((i + 1) % 3 == 0 && (i + 1) != left.length){
                    total.push(",");
                }
            } //total = ["6","5","4",",","3","2","1"]
            return total.reverse().join("") + "." + right;

        },
        toFloat1: function(var1,var2){
            if(var1 == undefined || var1 == ""){
                var1 = "0";
            }
            var1 = parseFloat(var1).toFixed(var2); //obj=123456.789
            var left = var1.split(".")[0].split("").reverse();//left = ["6","5","4","3","2","1"]
            var right = var1.split(".")[1]; //right = "789"
            var total = new Array();
            for (var i = 0; i < left.length; i++) {
                total.push(left[i]);
            } //total = ["6","5","4",",","3","2","1"]
            return total.reverse().join("") + "." + right;

        },
        /**
         * 去除金额千分位，并去除小数后面多余的0
         * @param var1
         * @returns {*|string|Node|void|never|{op, path, meta, value}}
         */
        fromFloat: function(var1){
            if(var1 == "" || var1 == undefined){
                return 0;
            }else {
                var oldMny = var1.replace(/,/g, '');
                if(oldMny.indexOf(".")>0){
                    oldMny = oldMny.replace(/0+?$/,"");//去除尾部多余的0
                    oldMny = oldMny.replace(/[.]$/,"");//如果最后一位是.则去掉
                }
                return oldMny;
            }

        },

        addPer:function(val){
            if(val == "" || val == undefined){
                return "0%";
            }else{
                return val + "%";
            }
        },
        removePer:function(val){
            if(val == "" || val == undefined){
                return 0;
            }else if(val.substring(val.length - 1) == "%"){
                return val.substring(0,val.length - 1);
            }else {
                return val;
            }
        },

        /**
         * 四舍五入到n位
         * @param num
         * @param val
         * @returns {*}
         */
        siSheWuRu:function(num ,val) {
            var num1 = num;
            var mi = 0;
            for(var i = 1;i<=val;i++){
                var a = num1 % 10;
                var b = parseInt(num1/10);
                if(b != 0){
                    if(a>=5){
                        num1 = parseInt(num1/10)+1;
                    }else {
                        num1 = parseInt(num1/10);
                    }
                }else {
                    return false;
                }
                mi++;
            }
            return num1 * Math.pow(10,mi)
        },
        /**
         * 页面初始化的时候传入dom的id，把金额数字格式化
         * @param ids
         */
        initNum:function (ids) {
            var idArray = ids.split(",");
            for(var i = 0; i< idArray.length; i++){
                var value = $("#" + idArray[i]).val();
                $("#" + idArray[i]).val(jp.toFloat(value,2))
            }
        },

        add: function(arg1,arg2){
            if(arg1 != 0 && arg2 != 0 && arg1 != undefined && arg2 != undefined && arg1 != '' && arg2 != ''){
                var arg1Str,arg1Len,arg2Str,arg2Len,m,res;
                arg1Str=arg1.toString().replace(".","");//获取金额字符串
                if(arg1.toString().indexOf(".") > -1){
                    arg1Len=arg1.toString().split(".")[1].length;
                }else {
                    arg1Len = 0;
                }
                arg2Str=arg2.toString().replace(".","");//获取金额字符串
                if(arg2.toString().indexOf(".") > -1){
                    arg2Len=arg2.toString().split(".")[1].length;
                }else {
                    arg2Len = 0;
                }
                if(arg1Len == arg2Len){
                    res = (parseInt(arg1Str) + parseInt(arg2Str)).toString()
                }else if(arg1Len > arg2Len){
                    m = arg1Len-arg2Len;
                    for(var i=0; i<m; i++){
                        arg2Str = arg2Str + "0";
                    }
                    res = (parseInt(arg1Str) + parseInt(arg2Str)).toString()
                }else {
                    m = arg2Len-arg1Len;
                    for(var i=0; i<m; i++){
                        arg1Str = arg1Str + "0";
                    }
                    res = (parseInt(arg1Str) + parseInt(arg2Str)).toString()
                }
                m = Math.max(arg1Len,arg2Len);
                var k = res.length - m;
                return parseFloat(res.substring(0,k)+"."+res.substring(k,res.length))

            }else if(arg1 == 0){
                return arg2;
            }else {
                return arg1;
            }
        },

        /**
         * 提交表单的时候，传入dom的id，把格式化金额数字转换成数字
         * @param ids
         */
        toNum:function (ids) {
            var idArray = ids.split(",");
            for(var i = 0; i< idArray.length; i++){
                if(idArray[i] == "" || idArray[i] == undefined){
                    continue;
                }else {
                    var value = $("#" + idArray[i]).val();
                    $("#" + idArray[i]).val(jp.fromFloat(value));
                }
            }
        },
        /**
         * 附件必传
         * @param ids
         */
        isFileUpload:function (listName) {
            var fileName = "";
            for(var i = 0;i<classFileLen;i++){
                var yesno = $("#"+listName+"_yesno"+i).val();
                if(yesno == "4395a1ad0cf74146b1fc8e45b379c7c1" &&
                    ($("#"+listName+"_classFile"+i).val() == undefined || $("#"+listName+"_classFile"+i).val() == "")){
                    fileName = fileName + $("#"+listName+"_fileTitle"+i).val() +",";
                }
            }
            if(fileName != ""){
                jp.error(fileName.substring(0,fileName.length-1)+"附件必传，请上传");
                return false;
            }else {
                return true;
            }
        },
		/*
		* params:
		*    id: 表单的jQuery ID 例如"#inputForm"
		*    succFuc, 成功后执行的回调函数
		*    beformSubmit：执行提交操作前执行的方法
		 */

		ajaxForm:function(id, succFuc, beforeSubmit){

            $(id).ajaxForm({
                dataType: 'json',
                beforeSubmit: function (arr, form, options) {
                    if(beforeSubmit){
                        beforeSubmit();
                    }
                    var isValidate = jp.validateForm(id);//校验表单
                    if(isValidate){
                        form.find("button:submit").button("loading");
                    }else{
                        return false;
                    }


                },
                error:function(xhr,textStatus){
                    if(xhr.status == 0){
                        jp.info("连接失败，请检查网络!")
                    }else if(xhr.status == 404){
                        var errDetail ="<font color='red'>404,请求地址不存在！</font>";
                        top.layer.alert(errDetail , {
                            icon: 2,
                            area:['auto','auto'],
                            title:"请求出错"
                        })
                    }else if(xhr.status && xhr.responseText){
                        var errDetail ="<font color='red'>"+ xhr.responseText.replace(/[\r\n]/g,"<br>").replace(/[\r]/g,"<br>").replace(/[\n]/g,"<br>")+"</font>";
                        top.layer.alert(errDetail , {
                            icon: 2,
                            area:['80%','70%'],
                            title:xhr.status+"错误"
                        })
                    }else{
                        var errDetail ="<font color='red'>未知错误!</font>";
                        top.layer.alert(errDetail , {
                            icon: 2,
                            area:['auto','auto'],
                            title:"真悲剧，后台抛出异常了"
                        })
                    }

                    $(id).find("button:submit").button("reset");

                },
                success: function (data, statusText, xhr, form) {
                    succFuc(data);
                    // form.find("button:submit").button("reset");
                }
            });

        },
        //打开对话框(添加修改)
        openSaveDialog: function(title,url,width,height){
            var auto = true;//是否使用响应式，使用百分比时，应设置为false
            if(width.indexOf("%")>=0 || height.indexOf("%")>=0 ){
                auto =false;
            }
            if(title == "审核"){
                top.layer.open({
                    type: 2,
                    // shade:0,
                    area: [width, height],
                    title: title,
                    auto:auto,
                    maxmin: true, //开启最大化最小化按钮
                    content: url,
                    btn: ['审核', '关闭'],
                    yes: function(index, layero){
                        var iframeWin = layero.find('iframe')[0]; //得到弹出的窗口对象，执行窗口内iframe页的方法：iframeWin.method();
                        iframeWin.contentWindow.save(title);//调用保存事件，在 弹出页内，需要定义save方法。处理保存事件。
                    },
                    cancel: function(index){
                    }
                });
            }else if(title == "反审"){
                top.layer.open({
                    type: 2,
                    // shade:0,
                    area: [width, height],
                    title: title,
                    auto:auto,
                    maxmin: true, //开启最大化最小化按钮
                    content: url,
                    btn: ['反审', '关闭'],
                    yes: function(index, layero){
                        var iframeWin = layero.find('iframe')[0]; //得到弹出的窗口对象，执行窗口内iframe页的方法：iframeWin.method();
                        iframeWin.contentWindow.save(title);//调用保存事件，在 弹出页内，需要定义save方法。处理保存事件。
                    },
                    cancel: function(index){
                    }
                });
            }else {
                top.layer.open({
                    type: 2,
                    // shade:0,
                    area: [width, height],
                    title: title,
                    auto:auto,
                    maxmin: true, //开启最大化最小化按钮
                    content: url,
                    btn: ['保存', '关闭'],
                    yes: function(index, layero){
                        var iframeWin = layero.find('iframe')[0]; //得到弹出的窗口对象，执行窗口内iframe页的方法：iframeWin.method();
                        iframeWin.contentWindow.save(title);//调用保存事件，在 弹出页内，需要定义save方法。处理保存事件。
                    },
                    cancel: function(index){
                    }
                });
            }

        },
        //打开对话框(查看)
        openViewDialog :function(title,url,width,height){
            var auto = true;//是否使用响应式，使用百分比时，应设置为false
            if(width.indexOf("%")>=0 || height.indexOf("%")>=0 ){
                auto =false;
            }
            top.layer.open({
                type: 2,
                area: [width, height],
                title: title,
                auto:auto,
                maxmin: true, //开启最大化最小化按钮
                content: url ,
                btn: ['关闭'],
                cancel: function(index){
                }
            });

        },

        //打开对话框(添加)
        openAddDialog: function(title,url,width,height,callback){
            var auto = true;//是否使用响应式，使用百分比时，应设置为false
            if(width.indexOf("%")>=0 || height.indexOf("%")>=0 ){
                auto =false;
            }
                top.layer.open({
                    type: 2,
                    area: [width, height],
                    title: title,
                    auto:auto,
                    maxmin: true, //开启最大化最小化按钮
                    content: url,
                    btn: ['确定', '关闭'],
                    yes: function(index, layero){
                        var iframeWin = layero.find('iframe')[0]; //得到弹出的窗口对象，执行窗口内iframe页的方法：iframeWin.method();
                        var data = iframeWin.contentWindow.save();//调用保存事件，在 弹出页内，需要定义save方法。处理保存事件。
                        callback(data);
                    },
                    cancel: function(index){
                    }
                });
        },
        /**
         *    xujin   拓展实现VBScript的DateAdd功能.
         *   参数:interval,字符串表达式，表示要添加的时间间隔.
         *   参数:number,数值表达式，表示要添加的时间间隔的个数.
         *   参数:date,时间对象.
         *   返回:新的时间对象.
         *---------------   DateAdd(interval,number,date)   -----------------
         */
        dateAdd: function (interval, number, date) {
            switch (interval) {
                case "y": {
                    date.setFullYear(date.getFullYear() + number);
                    return date;
                    break;
                }
                case "q": {
                    date.setMonth(date.getMonth() + number * 3);
                    return date;
                    break;
                }
                case "m": {
                    date.setMonth(date.getMonth() + number);
                    return date;
                    break;
                }
                case "w": {
                    date.setDate(date.getDate() + number * 7);
                    return date;
                    break;
                }
                case "d": {
                    date.setDate(date.getDate() + number);
                    return date;
                    break;
                }
                case "h": {
                    date.setHours(date.getHours() + number);
                    return date;
                    break;
                }
                case "m": {
                    date.setMinutes(date.getMinutes() + number);
                    return date;
                    break;
                }
                case "s": {
                    date.setSeconds(date.getSeconds() + number);
                    return date;
                    break;
                }
                default: {
                    date.setDate(d.getDate() + number);
                    return date;
                    break;
                }
            }
        },


        //打开子对话框(仅仅用作 父子layer弹窗之间交互数据使用)

        openChildDialog: function(title,url,width,height, parentObj){
            var auto = true;//是否使用响应式，使用百分比时，应设置为false
            if(width.indexOf("%")>=0 || height.indexOf("%")>=0 ){
                auto =false;
            }
          	top.layer.open({
          	    type: 2,
          	    area: [width, height],
          	    title: title,
          	    auto:auto,
          	    maxmin: true, //开启最大化最小化按钮
          	    content: url ,
          	    btn: ['确定', '关闭'],
          	    yes: function(index, layero){
          	         var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
          	         iframeWin.contentWindow.save(parentObj);//在子窗口定义save方法，负责实际业务逻辑的执行
          		  },
          	   cancel: function(index){
          	      }
          	});
          },
        validateForm: function (id) {
            return $(id).validate({
                errorPlacement: function(error, element) {
                    if (element.is(":checkbox")||element.is(":radio")){
                        error.appendTo(element.parent().parent().parent().parent());
                    }else  if (element.parent().is(".form_datetime") ||element.parent().is(".input-append") || element.is(".mydatepicker")){
                        error.appendTo(element.parent().parent());
                    }else{
                        error.insertAfter(element);
                    }
                }
            }).form();

        },
        go:function(url){//在当前选项卡跳转页面
			window.location.href = url;
        },
	    openTab:function(url,title, isNew){//isNew 为true时，打开一个新的选项卡；为false时，如果选项卡不存在，打开一个新的选项卡，如果已经存在，使已经存在的选项卡变为活跃状态。
	    	top.openTab(url,title,isNew);
	    },
        /**
		 * Ajax上传文件
         * @param fileObj
         * @param url
         * @param callback
         */
        uploadFile: function (fileObj, url,callback) {
            var data = new FormData(fileObj);
            // data.append("CustomField", "This is some extra data, testing");//如果要添加参数
            $.ajax({
                type: "POST",
                enctype: 'multipart/form-data',
                url: url,
                data: data,
                processData: false, //prevent jQuery from automatically transforming the data into a query string
                contentType: false,
                cache: false,
                timeout: 600000,
                success: function (result) {
                    callback(result);
                },
                error:function(xhr, textStatus){
                    if(xhr.status == 0){
                        jp.info("连接失败，请检查网络!")
                    }else if(xhr.status == 404){
                        var errDetail ="<font color='red'>404,请求地址不存在！</font>";
                        top.layer.alert(errDetail , {
                            icon: 2,
                            area:['auto','auto'],
                            title:"请求出错"
                        })
                    }else if(xhr.status && xhr.responseText){
                        var errDetail ="<font color='red'>"+ xhr.responseText.replace(/[\r\n]/g,"<br>").replace(/[\r]/g,"<br>").replace(/[\n]/g,"<br>")+"</font>";
                        top.layer.alert(errDetail , {
                            icon: 2,
                            area:['80%','70%'],
                            title:xhr.status+"错误"
                        })
                    }else{
                        var errDetail =xhr.responseText=="<font color='red'>未知错误!</font>";
                        top.layer.alert(errDetail , {
                            icon: 2,
                            area:['auto','auto'],
                            title:"真悲剧，后台抛出异常了"
                        })
                    }

                }
            })
        },
        downloadFile: function(url, name) {
            var $a = $("<a></a>").attr("href", url).attr("download", name);
            $a[0].click();
        },
        /**
         * 返回当前活跃的tab页面关联的iframe的Windows对象，方便layer弹窗调用父页面的方法。
         */
        getParent: function () {
            return top.getActiveTab()[0].contentWindow;
        },
        getSeriesData: function (data,b) {
            var series = [];
            if(b){
                $.each(data,function(key,values){
                    var markDataArr = [];
                    var markData = {};
                    for(var i = 0; i<values.length; i++){
                        markData = {
                            name : key,
                            value: values[i],
                            xAxis: i,
                            yAxis: values[i]
                        }
                        markDataArr.push(markData);
                    }
                    series.push({
                        name: key,
                        type: 'bar',
                        data: values,
                        markPoint: {
                            data: markDataArr
                        }
                    })

                })
            }else {
                $.each(data,function(key,values){
                    series.push({
                        name: key,
                        type: 'bar',
                        data: values
                    })

                })
            }
            return series;
        },

        initJsonD: function($id){
            var conditions ="";
            var beanName ="";
            if($id.attr("data-beanName") != '' || $id.attr("data-beanName") != undefined){
                beanName = $id.attr("data-beanName");
            }

            if($id.attr("data-parentId") == '' || $id.attr("data-parentId") == undefined){
            }else {
                var pId = $id.attr("data-parentId").split("|");
                var pKey = $id.attr("data-parentKey").split("|");
                var pVal = $id.attr("data-parentVal").split("|");
                $.each(pId,function (k,y) {
                    if($("#"+y).val()!=null && $("#"+y).val()!=''){
                        if(conditions == ''){
                            conditions = pKey[k]+"|"+$("#"+y).val();
                        }else {
                            conditions = conditions + "," + pKey[k]+"|"+$("#"+y).val();
                        }
                    }else if(pVal[k]!=null && pVal[k]!=''){
                        if(conditions == ''){
                            conditions = pKey[k]+"|"+pVal[k];
                        }else {
                            conditions = conditions + "," + pKey[k]+"|"+pVal[k];
                        }
                    }
                })
            }
            var jsonD = {
                tableName:$id.attr("data-tableName"),
                conExtral:$id.attr("data-conExtral"),
                colName:$id.attr("data-colName"),
                conditions:conditions,
                beanName:beanName
            }
            return jsonD;
        },
        initSelectLD: function ($id,url) {
            if($id.attr("data-tableName") != undefined && $id.attr("data-tableName") != ''){//判断是否是下拉关联select
                var jsonD = jp.initJsonD($id)
                if($id.attr("data-parentVal") == '' || $id.attr("data-parentVal") == undefined || $id.attr("data-value") != ''){
                    jp.post(url,jsonD,function (data) {
                        $id.append('<option value=""></option>');
                        $.each(data,function (idx,data1) {
                            $id.append('<option value="'+data1.id+'">'+data1[$id.attr("data-colName")]+'</option>');
                        })
                        if($id.attr("data-value") != ''){
                            $id.val($id.attr("data-value"));
                        }
                    })
                }
                $id.change(function() {
                    var opt=$(this).val();
                    if($id.attr("data-select-childid") != '' && opt != ''){
                        var $id1 = $("#"+$id.attr("data-select-childid"));
                        var jsonD1 = jp.initJsonD($id1)
                        $id1.empty();//先清空
                        jp.post(url,jsonD1,function (data) {
                            if(data.length <= 0){
                                $id1.append('<option value="">无数据</option>');
                            }else {
                                $id1.append('<option value=""></option>');
                                $.each(data,function (idx,data1) {
                                    $id1.append('<option value="'+data1.id+'">'+data1[$id1.attr("data-colName")]+'</option>');
                                })
                            }

                        })
                    }
                })
            }
        },
        addClassFun:function (ids,className) {
            var idArr = ids.split(",");
            for(var i=0;i<idArr.length;i++){
                if($("#"+idArr[i]).hasClass(className)){
                }else {
                    $("#"+idArr[i]).addClass(className);
                }

            }
        },
        removeClassFun:function (ids,className) {
            var idArr = ids.split(",");
            for(var i=0;i<idArr.length;i++){
                if($("#"+idArr[i]).hasClass(className)){
                    $("#"+idArr[i]).removeClass(className);
                }
            }
        },
        tabTableInput:function (tableId, inputType) {
        var rowInputs = [];
        var trs = $("#" + tableId).find("tr");
        var inputRowIndex = 0;
        $.each(trs, function(i, obj) {
            if ($(obj).find("th").length > 0) { //跳过表头
                return true;
            }
            var rowArray = [];
            var thisRowInputs;
            if (!inputType) { //所有的input
                thisRowInputs = $(obj).find("input:not(:disabled):not(:hidden):not([readonly])");
            } else {
                thisRowInputs = $(obj).find("input:not(:disabled):not(:hidden):not([readonly])[type=" + inputType + "]");
            }
            if (thisRowInputs.length == 0) {
                return true;
            }
            thisRowInputs.each(function(j) {
                $(this).attr("_r_", inputRowIndex).attr("_c_", j);
                rowArray.push( {
                    "c" : j,
                    "input" : this
                });
                $(this).keydown(function(evt) {
                    var r = $(this).attr("_r_");
                    var c = $(this).attr("_c_");
                    var tRow
                    if (evt.which == 38) { //上
                        if (r == 0)
                            return;
                        r--; //向上一行
                        tRow = rowInputs[r];
                        if (c > tRow.length - 1) {
                            c = tRow.length - 1;
                        }
                        $(rowInputs[r].data[c].input).focus();
                    } else if (evt.which == 40) { //下
                        if (r == rowInputs.length - 1) { //已经是最后一行
                            return;
                        }
                        r++;
                        tRow = rowInputs[r];
                        if (c > tRow.length - 1) {
                            c = tRow.length - 1;
                        }
                        $(rowInputs[r].data[c].input).focus();
                    } else if (evt.which == 37) { //左
                        if (r == 0 && c == 0) { //第一行第一个,则不执行操作
                            return;
                        }
                        if (c == 0) { //某行的第一个,则要跳到上一行的最后一个,此处保证了r大于0
                            r--;
                            tRow = rowInputs[r];
                            c = tRow.length - 1;
                        } else { //否则只需向左走一个
                            c--;
                        }
                        $(rowInputs[r].data[c].input).focus();
                    } else if (evt.which == 39) { //右
                        tRow = rowInputs[r];
                        if (r == rowInputs.length - 1 && c == tRow.length - 1) { //最后一个不执行操作
                            return;
                        }
                        if (c == tRow.length - 1) { //当前行的最后一个,跳入下一行的第一个
                            r++;
                            c = 0;
                        } else {
                            c++;
                        }
                        $(rowInputs[r].data[c].input).focus();
                    }

                });
            });
            rowInputs.push( {
                "length" : thisRowInputs.length,
                "rowindex" : inputRowIndex,
                "data" : rowArray
            });
            inputRowIndex++;
        });
    }

    }

})(jQuery);


